package appx.craft.droid.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import appx.craft.droid.R;
import appx.craft.droid.bean.FeedBean;
import appx.craft.droid.bean.JSONParams;
import appx.craft.droid.stricky.StickyListHeadersListView;
import appx.craft.droid.stricky.StickyListHeadersListView.OnHeaderClickListener;
import appx.craft.droid.uc.FeedAdapter;
import appx.craft.droid.uc.IHeaderListener;
import appx.craft.droid.uc.ProfileAdapter;
import appx.craft.droid.uc.TabMenuClickListener;
import appx.craft.droid.utils.Constance;
import appx.craft.droid.utils.JSONParser;
import appx.craft.droid.utils.Log;
import appx.craft.droid.utils.UtilityHelper;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ProfileSettingsActivity extends FragmentActivity implements OnScrollListener, AdapterView.OnItemClickListener,
OnHeaderClickListener,TabMenuClickListener,onFeedCommentClickListner,IHeaderListener{
	
	private final String TAG = ProfileSettingsActivity.class.getCanonicalName();

	public static final String TAG_STATUS_MESSAGE = "statusmsg";
	public static final String TAG_STATUS = "status";
	public static final String TAG_PHOTOS_ARRAY = "Photos";

	public static final String TAG_PROFILE_ID = "ProfileID";
	public static final String TAG_FEED_ID = "FeedID";
	public static final String TAG_FILE_PATH = "FilePath";
	public static final String TAG_CREATED = "Created";
	public static final String TAG_Name = "Name";
	public static final String TAG_CAPTION = "Caption";

	private int startIndex = 0;
	
	private static final String KEY_LIST_POSITION = "KEY_LIST_POSITION";
	
	private int firstVisible;

	public ProfileAdapter mFeedAdapter;
	
	private StickyListHeadersListView stickyList;
	
	// image cache idea
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	
	public DisplayImageOptions mOptions;
	
	private boolean instanceStateSaved;
	
	TextView textView_timestemp;
	
	@Override
	protected void onCreate(Bundle saveInstance) {
		super.onCreate(saveInstance);
		Log.d(TAG, "[onCreate ]");
		setContentView(R.layout.activity_profile_settings);
		
		mOptions = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.ic_launcher)
		.resetViewBeforeLoading().cacheInMemory().cacheOnDisc().build();
		
		textView_timestemp = (TextView)findViewById(R.id.textView_timestemp);
		textView_timestemp.setVisibility(View.GONE);
		
		stickyList = (StickyListHeadersListView) findViewById(R.id.stickyListHeadersListView);
		stickyList.setSmoothScrollbarEnabled(true);
		stickyList.setAreHeadersSticky(false);
		stickyList.setDivider(new ColorDrawable(0x0000ffff));
		stickyList.setDividerHeight(1);
		stickyList.setOnItemClickListener(this);
		stickyList.setOnHeaderClickListener(this);

		if (saveInstance != null) {
			firstVisible = saveInstance.getInt(KEY_LIST_POSITION);
		}
		
		mFeedAdapter = new ProfileAdapter(this, imageLoader, mOptions);
		stickyList.setAdapter(mFeedAdapter);
		stickyList.setSelection(firstVisible);
		
		startIndex = 0;
		
		if (UtilityHelper.isOnline(ProfileSettingsActivity.this)) {
			
			FeedBean mTopBeans = new FeedBean();

			mTopBeans.setTypeID(Constance.VIEW_PROFILE_ICONS);
			mTopBeans.setFeedID("");
			mTopBeans.setProfileID("");
			
			mTopBeans.setName("testaccount@gmail.com");
			mTopBeans.setCaptionText("");
			mTopBeans.setFilePath("");
			mTopBeans.setLikeCounter("0");
			Calendar c = Calendar.getInstance();
			SimpleDateFormat df = new SimpleDateFormat(
					"dd MMM yyyy hh:mm a");
			String formattedDate = df.format(c.getTime());
			mTopBeans.setCreatedDateTime(formattedDate);
			
			mFeedAdapter.addFirstFeed(mTopBeans);
			
			
			new getFeedList().execute(new Integer[] { startIndex });
			
		} else {
			Toast.makeText(getApplicationContext(),
					"Please check internet connection !!!", Toast.LENGTH_LONG)
					.show();
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		instanceStateSaved = true;
		outState.putInt(KEY_LIST_POSITION, firstVisible);
	}

	
	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG, "[ onStart ]");
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "[ onStop ]");
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "[ onPause ]");
	}
	
	@Override
	protected void onDestroy() {
		Log.d(TAG, "[ onDestroy ]");
		startIndex = 0;
		imageLoader.clearMemoryCache();
		imageLoader.clearDiscCache();
		if (!instanceStateSaved) {
			Log.d(TAG, "[ stop imageLoader ]");
			imageLoader.stop();
		}
		super.onDestroy();
	}

	@Override
	public void onMenuItemClick(int buttonID) {
	}

	@Override
	public void onHeaderClick(StickyListHeadersListView l, View header,
			int itemPosition, long headerId, boolean currentlySticky) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		
	}
	
	class getFeedList extends AsyncTask<Integer, Void, Integer> {

		private ArrayList<FeedBean> mTempFeedList;
		private int tempIndex;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mTempFeedList = new ArrayList<FeedBean>();
		}

		@Override
		protected Integer doInBackground(Integer... params) {

			int result = 0;
			try {

				ArrayList<JSONParams> mArrayParams;
				JSONParams mObj$Params;
				mArrayParams = new ArrayList<JSONParams>();

				mObj$Params = new JSONParams();
				mObj$Params.setStrKey(Constance.PARAM_OFFSET);
				mObj$Params.setStrvalue(String.valueOf(params[0]));
				tempIndex = params[0];
				mArrayParams.add(mObj$Params);

				mObj$Params = new JSONParams();
				mObj$Params.setStrKey(Constance.PARAM_LIMIT);
				mObj$Params.setStrvalue(String.valueOf(Constance.LIMIT_PAGE)); // default
																				// 10
																				// limit
				mArrayParams.add(mObj$Params);

				JSONArray mPhotosJsonArray = null;
				// Creating JSON Parser instance
				JSONParser jParser = new JSONParser();

				// getting JSON string from URL
				JSONObject mJson = jParser.getJSONFromUrl(
						Constance.GET_FEED_URL, mArrayParams);
				
				Log.d(TAG, "[ mJSON ]" + mJson.toString());
				
				String mStatus = mJson.getString(TAG_STATUS);
				String mMessage = mJson.getString(TAG_STATUS_MESSAGE);

				Log.d(TAG, "[ STATUS ]" + mStatus);
				Log.d(TAG, "[ MESSAGE ]" + mMessage);

				if (mMessage.equalsIgnoreCase("Ok")) {
					result = 200;
					// Getting Array of TAG_PHOTOS_ARRAY
					mPhotosJsonArray = mJson.getJSONArray(TAG_PHOTOS_ARRAY);

					FeedBean mBeanofFeeds;

					if (mPhotosJsonArray.length() > 0) {

						for (int i = 0; i < mPhotosJsonArray.length(); i++) {

							mBeanofFeeds = new FeedBean();
							JSONObject mObjectMessage = mPhotosJsonArray
									.getJSONObject(i);

							String mProfileName = new String(
									mObjectMessage.getString(TAG_Name));
							String mCaption = new String(
									mObjectMessage.getString(TAG_CAPTION));
							String mFeedID = new String(
									mObjectMessage.getString(TAG_FEED_ID));
							String mFilePath = new String(
									mObjectMessage.getString(TAG_FILE_PATH));
							String mFileCreated = new String(
									mObjectMessage.getString(TAG_CREATED));

							// Download View Type
							mBeanofFeeds.setTypeID(Constance.VIEW_DOWNLOAD);
							mBeanofFeeds.setProfileID("");
							mBeanofFeeds.setFeedID(mFeedID);
							mBeanofFeeds.setName(mProfileName);
							mBeanofFeeds.setDisplayName("");
							mBeanofFeeds.setCaptionText(mCaption);
							mBeanofFeeds.setLikeCounter("0");
							mBeanofFeeds.setFilePath(mFilePath);
							mBeanofFeeds.setCreatedDateTime(mFileCreated);

							if (mTempFeedList.isEmpty()) {
								mTempFeedList.clear();
							}

							mTempFeedList.add(mBeanofFeeds);

						}
					} else {
						result = 401;
					}

				} else {
					result = -1;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			return result;
		}

		@Override
		protected void onPostExecute(Integer result) {

			if (result > -1) {

				if (result == 200) {
					for (FeedBean mMessage : mTempFeedList) {
						mFeedAdapter.addNewFeedItem(mMessage);
					}
					stickyList.setOnScrollListener(ProfileSettingsActivity.this);
					
				} else if (result == 401) {
					startIndex = tempIndex != 0 ? (tempIndex - 10) : 0;
				}
			}
		}

	}

	@Override
	public void onStreamCommentClick(int position) {
	}

	@Override
	public void onStreamLikerListClick(int position) {
		
	}

	@Override
	public void onStreamPhotoSlidingClick(int position) {
	}

	@Override
	public void onProfileIconClick(int position) {
		startActivity(new Intent(ProfileSettingsActivity.this,FeedSettingsActivity.class));
	}

	public void resetFeedHeader(final String timestemp,final boolean inVisible){
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				
				if(!inVisible){
					textView_timestemp.setText(timestemp);	
				}else{
					textView_timestemp.setVisibility(View.GONE);
				}
			  	
			}
		});
	}

	@Override
	public void resetHeaderView(int position) {
		
		if(!textView_timestemp.isShown()){
			textView_timestemp.setVisibility(View.VISIBLE);	
		}
		if(position > 0){
			
			final String latestDate = UtilityHelper.extractDateFromTimeStemp(ProfileAdapter.mFeedMessageList.get(position).getCreatedDateTime());
			resetFeedHeader(latestDate,false);	
		}else{
			resetFeedHeader("",true);	
		}
		
	}
}
